<template>
  <div class="container">
    <a-modal
      v-model:visible="visible"
      v-model:draggable="draggable"
      :title="title"
      @cancel="handleCancel"
      @before-ok="onBeforeOk"
    >
      <a-select v-model="roleIdArr" placeholder="角色" multiple >
        <a-option v-for="(role,index) in roles" :key="index" :value="role.id">{{role.name}}</a-option>
      </a-select>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue';
import {useI18n} from 'vue-i18n';
import { roleAssign, roleIds} from '@/api/user';
import {rolesList} from '@/api/role';
import {Message} from "@arco-design/web-vue";

export default defineComponent({
    setup(props, context) {
      const { t } = useI18n();
      const roleIdArr = ref<string[]>([]);
      const roles = ref([]);
      const uid = ref('');
      const loadRole = async () => {
        const { data } = await rolesList();
        roles.value =data
      };
      loadRole();

      const onBeforeOk = async (done: (arg: boolean) => void) => {
        const isOk =   roleIdArr.value.length>0;
        if (!isOk) {
          Message.error('请选择角色');
          return false;
        }
        await roleAssign({userId:uid.value,roleIds:roleIdArr.value});
        Message.success('操作成功!');
        return done(isOk);
      };




      return {
        t,
        roles,
        roleIdArr,
        onBeforeOk,
        uid
      };
    },
    data() {
      return {
        visible: false,
        draggable: true,
        title: '',
        loading: false,
      };
    },
    methods: {
      open(id: string) {
        this.visible = true;
        this.uid = id
        this.title = '角色授权';
        this.queryRoleIds(id);
      },
      async queryRoleIds(id: string) {
        const { data } = await roleIds(id);
        this.roleIdArr = data
      },
      handleCancel() {
        this.visible = false;
        this.roleIdArr = [];
        this.uid = ''
      }
    },
  });
</script>

<style scoped lang="less">
  .container {
    padding: 20px;

    .keep-margin {
      margin-bottom: 20px;
    }
  }

  .form {
    width: 420px;
  }
</style>
